package com.enotary.flutter_obs;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.List;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.EventChannel;

/**
 * FlutterObsPlugin obs断点续传上传文件 回调上传进度及结果
 */
public class FlutterObsPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel mChannel;
    private EventChannel mEventChannel;
    private ObsJavaEventChannel mEventHandler;
    private static final String methodChannel = "com.obs.navigator";
    public static final String eventChannel = "com.obs/eventChannel";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private String mFilesDir;
    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        mChannel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), methodChannel);
        mChannel.setMethodCallHandler(this);
        mEventHandler = ObsJavaEventChannel.getInstance();
        mEventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), eventChannel);
        mEventChannel.setStreamHandler(mEventHandler);
        Context context = flutterPluginBinding.getApplicationContext();
        mFilesDir = context.getFilesDir().getAbsolutePath();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        String method = call.method;
        if ("getPlatformVersion".equals(method)) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if ("startUpload".equals(method)) {
            List<HashMap<String, Object>> list = call.argument("files");
            //使用EventChannel时，Flutter端会注册一个监听器，这个监听器会在主线程上执行回调函数--并不会 改为主线程handler通知执行
            result.success(mEventHandler != null && mEventHandler.startUpload(list, mFilesDir, (data) -> {
                runOnUiThread(()->{
                    if(mEventHandler != null) mEventHandler.eventSink(data);
                });
            }));
        } else if ("cancelUpload".equals(method)) {
            String cancelKey = call.argument("filePath");
            result.success(mEventHandler != null && mEventHandler.cancelUpload(cancelKey));
        } else {
            result.notImplemented();
        }
    }

    private void runOnUiThread(Runnable runnable){
        mHandler.post(runnable);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        if(mChannel != null) mChannel.setMethodCallHandler(null);
        if(mEventChannel != null) mEventChannel.setStreamHandler(null);
    }
}
